<?php

namespace Admin\Controller;

use Common\Common\AdminController;
use Common\Top;
use Common\Utils;
use Common\Sms;

class WithdrawController extends AdminController
{

    /**
     * 更新凭证
     */
    public function updateWithDrawProof()
    {
        if (IS_POST && IS_AJAX) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 0;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $auditState = I('state', 0, 'int');
            $id = I("id", 0, 'int');
            $state = M('AccountWithdraw')->where('id=' . $id)->field('state')->find();

            if ($auditState == 4 && $state['state'] == 4) {

                $updateData['proof_type'] = I('proof_type');
                $updateData['proof_code'] = I('proof_code');
                $updateResult = M('account_withdraw')->where("id = '{$id}'")->save($updateData);

                if ($updateResult == 1) {
                    $data['status'] = 1;
                    $data['msg'] = '操作成功';
                    $this->ajaxreturn($data);
                } else {
                    $data['status'] = 0;
                    $data['msg'] = '操作失败';
                    $this->ajaxreturn($data);
                }
            }
        }
    }

    /**
     * 供应商审核提现
     */
    public function providerAuditWithDraw()
    {
        if (IS_POST && IS_AJAX) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 2;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $auditState = I('state', 0, 'int');
            $id = I("id", 0, 'int');
            $keyid = Utils::getDecrypt(I('keyid'));

            if ($id != $keyid) {
                $data['status'] = 0;
                $data['msg'] = '操作失败';
                $this->ajaxReturn($data);
            }

            $statePassData['state'] = I('state');
            $statePassData['update_time'] = date("Y-m-d H:i:s", time());

            if ($auditState == Top::ApplyStatePass) {
                $statePassResult = M('account_withdraw')->where('id = ' . $id)->save($statePassData);

                $withdrawInfo = M('account_withdraw')->where("id = '{$id}'")->find();
                $providerName = $withdrawInfo['entity_name'];
                $template = array(
                    'touser' => 'oK9HQsxpTtSSMURoe9NJp3lnpP_0',
                    'template_id' => '4R5wh3fhajnICPrU5LNDJ_6d7brRNbkQOMI9AX_D2gY',

                    'data' => array(
                        'first' => array('value' => urlencode("您好, 供应商: {$providerName} 提交提现申请, 请登录系统查看"), 'color' => "#000"),
                        'keyword1' => array('value' => urlencode(Utils::getYuan($withdrawInfo['amount'])), 'color' => "#000"),
                        'keyword2' => array('value' => urlencode(date("Y-m-d H:i:s", time())), 'color' => '#000'),
                        'keyword3' => array('value' => urlencode('大旅平台'), 'color' => '#000'),
                    )
                );

                if ($statePassResult) {
                    $this->send_tpl($template);

                    $data['status'] = 1;
                    $data['msg'] = '操作成功';
                    $this->ajaxReturn($data);
                } else {
                    $data['status'] = 2;
                    $data['msg'] = '操作失败';
                    $this->ajaxReturn($data);
                }
            }

            if ($auditState == Top::ApplyStateReject && !empty($id)) {
                $data['memo'] = I('post.memo');
                $data['state'] = I('post.state', 0, 'int');
                $data['update_time'] = date("Y-m-d H:i:s", time());

                $withdraw = M('account_withdraw')->where('id=' . $id)->setField($data);
                if ($withdraw) {
                    $data['status'] = 1;
                    $this->ajaxReturn($data);
                } else {
                    $data['status'] = 0;
                    $data['msg'] = '系统出错啦';
                    $this->ajaxReturn($data);
                }
            }
        }
    }


    /**
     * 财务审核
     */
    public function financeAuditWithDraw()
    {
        if (IS_POST && IS_AJAX) {
            if ($this->warnStatus == '10404') {
                $data['status'] = 2;
                $data['msg'] = $this->warnInfo;
                $this->ajaxreturn($data);
            }

            $auditState = I('state', 0, 'int');
            $id = I("id", 0, 'int');
            $keyid = Utils::getDecrypt(I('keyid'));

            if ($id != $keyid) {
                $data['status'] = 0;
                $data['msg'] = '操作失败';
                $this->ajaxReturn($data);
            }

            $state = M('AccountWithdraw')->where('id=' . $id)->field('state')->find();
            $account_transaction = D('AccountWithdraw')->transaction($id);

            $statePassData['state'] = I('state');
            $statePassData['update_time'] = date("Y-m-d H:i:s", time());

            if ($auditState == Top::ApplyStateFinish && !empty($id)) {
                if ($account_transaction['1']) {
                    if ($account_transaction['2']['account_balance'] - $account_transaction['0']['amount'] >= 0) {
                        if ($auditState == Top::ApplyStateFinish && $state['state'] == Top::ApplyStateReject) {
                            $data['status'] = 3;
                            $data['msg'] = '当前申请已审核';
                            $this->ajaxReturn($data);
                        } else {
                            $postCode = I('code');
                            $code = session('providerWithdrawCode');

                            if ($code == $postCode) {
                                session('providerWithdrawCode', null);
                                $date['state'] = $auditState;
                                $date['memo'] = '';
                                $date['proof_type'] = I('proof_type');
                                $date['proof_code'] = I('proof_code');
                                $date['update_time'] = date('Y-m-d H:i:s', time());

                                M('account_withdraw')->startTrans();
                                $withdraw = M('account_withdraw')->where('id=' . $id)->setField($date);

                                $operatorId = $account_transaction['0']['operator_id'];
                                $data = array(
                                    'operator_id' => $operatorId,
                                    'sn' => Utils::getSn(), //随机生成编号
                                    'account' => $account_transaction['0']['account'],
                                    'entity_type' => $account_transaction['0']['entity_type'],
                                    'entity_id' => $account_transaction['0']['entity_id'],
                                    'action' => '提现',
                                    'balance' => $account_transaction['2']['account_balance'] - $account_transaction['0']['amount'],
                                    'amount' => -$account_transaction['0']['amount'],
                                    'create_time' => date('Y-m-d H:i;s', time()),
                                    'remark' => 'top_account_withdraw.id:' . I('id'),
                                    'object_id' => I('id'),
                                    'object_type' => Top::ObjectTypeWithDraw,
                                    'object_name' => '提现',
                                    'memo' => '',
                                );

                                $transaction_id = M('account_transaction')->add($data);

                                $entity = M('account_withdraw')->field('entity_id')->find($id);
                                $entityId = $entity['entity_id'];
                                //计算provider表中的金额
                                $balanceinfo['account_balance'] = $account_transaction['1']['account_balance'] - $account_transaction['0']['amount'];
                                $provider_balance = M('provider')->where('id=' . $entityId)->save($balanceinfo);

                                $providerAccountResult = M('provider_account')->where("provider_id = '{$entityId}' && operator_id = '{$operatorId}'")->setDec('account_balance', $account_transaction['0']['amount']);

                                if ($withdraw && $transaction_id && $provider_balance && $providerAccountResult) {
                                    M('account_withdraw')->commit();
                                    $mobile = M('provider')->field('mobile')->find($entity['entity_id']);
                                    Sms::Send($mobile['mobile'], '您的提现申请已受理，提现金额：' . Utils::getYuan($account_transaction['0']['amount']) . '，详情请登录系统查看', $this->cdkey, $this->pwd, $this->signature, $this->smsOperatorId);
                                    $data['status'] = 1;
                                    $this->ajaxReturn($data);
                                } else {
                                    M('account_withdraw')->rollback();
                                    $data['status'] = 0;
                                    $data['msg'] = '系统出错啦';
                                    $this->ajaxReturn($data);
                                }
                            } else {
                                $data['status'] = 9;
                                $data['msg'] = '请勿重复提交';
                                $this->ajaxReturn($data);
                            }
                        }
                    } else {
                        $data['status'] = 5;
                        $data['msg'] = '账户总额不足';
                        $this->ajaxReturn($data);
                    }
                } else {
                    $data['status'] = 6;
                    $data['msg'] = '当前账户已冻结或者用户状态禁用';
                    $this->ajaxReturn($data);
                }
            }
        }
    }


    public function index()
    {
        $_SESSION['providerWithdrawCode'] = 400;
        $entityType = Top::EntityTypeProvider;
        $name = trim(I('names'));
        $operatorId = session('operator_id');
        $state = I('state');
        $startTime = !empty(I('start_time')) ? I('start_time') : date("2015-05-01", time());
        $endTime = !empty(I('end_time')) ? I('end_time') : date('Y-m-d', time());
        $roleId = session('role_id');

        if ($roleId == 1 || $roleId == 185 || $roleId == 186) {
            if ($state != 0) {
                $where = "(entity_name like '%%$name%%' or full_name like '%%$name%%' or amount = '{$name}') && entity_type = '{$entityType}' && state = '{$state}' && (create_time >= '{$startTime} {$this->dateStart}' && create_time <= '{$endTime} {$this->dateEnd}')";
            } else {
                $where = "(entity_name like '%%$name%%' or full_name like '%%$name%%'  or amount = '{$name}') && entity_type = '{$entityType}' && (create_time >= '{$startTime} {$this->dateStart}' && create_time <= '{$endTime} {$this->dateEnd}')";
            }
        } else {
            if ($state != 0) {
                $where = "operator_id = '{$operatorId}' && entity_type = '{$entityType}' && (entity_name like '%%$name%%' or full_name like '%%$name%%'  or amount = '{$name}') && state = '{$state}' && (create_time >= '{$startTime} {$this->dateStart}' && create_time <= '{$endTime} {$this->dateEnd}')";
            } else {
                $where = "operator_id = '{$operatorId}' && entity_type = '{$entityType}' && (entity_name like '%%$name%%' or full_name like '%%$name%%'  or amount = '{$name}') && (create_time >= '{$startTime} {$this->dateStart}' && create_time <= '{$endTime} {$this->dateEnd}')";
            }
        }

        $record_sum = M('account_withdraw')->where($where)->count(); //记录总数
        $pageInfo = Utils::pages('account_withdraw', $where, C('PAGE_SET'), $order = " id desc ");

        $this->state = $state;
        $this->total = $record_sum;
        $this->info = $pageInfo['info'];
        $this->page = $pageInfo['page'];
        $this->assign('name', $name);
        $this->assign('startTime', $startTime);
        $this->assign('endTime', $endTime);
        $this->display();
    }


    function showAccountBalance()
    {
        if (IS_AJAX && IS_POST) {
            $where['provider_id'] = I('id');
            $where['operator_id'] = I('oid');
            $info = M('provider_account')->where($where)->field('id,account_balance,operator_id')->find();

            if ($info) {
                $data['status'] = 1;
                $data['account_balance'] = Utils::getYuan($info['account_balance']);
                $this->ajaxReturn($data);
            } else {
                $data['status'] = 2;
                $data['msg'] = '查看失败';
                $this->ajaxReturn($data);
            }
        }
    }


    function showFullName()
    {
        if (IS_AJAX && IS_POST) {
            $where['id'] = I('id');
            $providerInfo = M('provider')->where($where)->field('id,full_name')->find();

            if ($providerInfo) {
                $data['status'] = 1;
                $data['full_name'] = $providerInfo['full_name'];
                $this->ajaxReturn($data);
            } else {
                $data['status'] = 2;
                $data['msg'] = '查看失败';
                $this->ajaxReturn($data);
            }
        }
    }

}
